using System;
using System.Collections;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.Policy;
using PHSRAG.Utility;

namespace PHSRAG.Insight21.FormsManagement
{
    /// <summary>
    /// AddItem page lets the user select the type of the question that is to be added
    /// </summary>
    public partial class AddItemPage : BasePage
    {
        #region Constants

        private const string AddItemScriptKey = "addItemScriptKey_CF70A5D1-B194-4c23-9866-7DD16DD38E51";
        private const string SelectedQuestionnaireIdKey = "SelectedQuestionnaireIdKey_CF70A5D1-B194-4c23-9866-7DD16DD38E51";
        private const string SelectedQuestionnaireVersionIdKey = "SelectedQuestionnaireVersionIdKey_CF70A5D1-B194-4c23-9866-7DD16DD38E51";

        #endregion

        #region Instance members (private)

        private ICachePolicy cachePolicy;
        private ICachePolicy pageCachePolicy;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the selected questionnaire's id
        /// </summary>
        private int SelectedQuestionnaireID
        {
            get { return int.Parse(pageCachePolicy.GetCachedObject(SelectedQuestionnaireIdKey).ToString()); }
        }


        /// <summary>
        /// Gets the selected questionnaire version's id
        /// </summary>
        private int SelectedQuestionnaireVersionID
        {
            get { return int.Parse(pageCachePolicy.GetCachedObject(SelectedQuestionnaireVersionIdKey).ToString()); }
        }

        #endregion

        #region Page Events

        /// <summary>
        /// Stores the incoming data in local cache.
        /// </summary>
        /// <param name="sender">Control that raised the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (header.ModuleName == InsightUtilities.Constants.Modules.Admin)
                {
                    adminHumansSubNavigation.Visible = true;
                    coiSubNavigation.Visible = false;
                }
                else if (header.ModuleName == InsightUtilities.Constants.Modules.COI)
                {
                    adminHumansSubNavigation.Visible = false;
                    coiSubNavigation.Visible = true;
                }

                breadCrumb.Add(" Forms Management",
                    Settings.GetKeyValue("SubNavigation.Admin.humansURL", ""),
                    Settings.GetKeyValue("BreadCrumb.SummaryPageLevel", 1));

                if (!IsPostBack)
                {
                    Hashtable incomingData = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                    if (incomingData != null)
                    {
                        pageCachePolicy.Cache(SelectedQuestionnaireIdKey, incomingData[Keys.QuestionnaireIdKey].ToString());
                        pageCachePolicy.Cache(SelectedQuestionnaireVersionIdKey, incomingData[Keys.QuestionnaireVersionIdKey].ToString());
                        pageCachePolicy.UnCache(Keys.IncomingDataKey);
                    }
                }
            }
            catch
            {
                annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                annunciator.Message = "Failed to load the page.";
            }
            finally
            {
                if (coiSubNavigation.Visible)
                {
                    coiSubNavigation.SelectedLink = "Forms Management";
                    coiSubNavigation.AccessLevel = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask;
                }
            }
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Page Initialization
        /// </summary>
        /// <param name="e">Arguments associated with the event.</param>
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            base.OnInit(e);
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
        }

        #endregion

        #region Events

        /// <summary>
        /// Redirects the user to allow him to add a new question (of the selected type)
        /// </summary>
        /// <param name="sender">Control that raised the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnAddItem(object sender, EventArgs e)
        {
            try
            {
                Hashtable dictionary = new Hashtable();
                dictionary.Add(Keys.QuestionnaireIdKey, SelectedQuestionnaireID);
                dictionary.Add(Keys.QuestionnaireVersionIdKey, SelectedQuestionnaireVersionID);
                dictionary.Add(Keys.QuestionnaireItemIdKey, 0);
                dictionary.Add(Keys.QuestionnaireItemTypeKey, questionType.SelectedValue);
                cachePolicy.Cache(Keys.IncomingDataKey, dictionary);

                Response.Redirect(Settings.GetKeyValue("SubNavigation.Admin.Humans.ItemEditorURL", "ItemEditor.aspx"), false);
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link before the header or the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                adminSubNavigation.Reset();
                adminHumansSubNavigation.Reset();
                coiSubNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        #endregion
    }
}